﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;

namespace Meraz.Core.Repositories
{
    public interface IFileRepository : IRepository<FileInfo, string> { 
        DirectoryInfo BaseDirectory { get; set; } 
        void Add(string fileName, Stream stream); 
    }
    public interface ITwitterFileRepository : IFileRepository { }
    public class TwitterFileRepository : FileRepositoryBase, ITwitterFileRepository
    {
        public TwitterFileRepository(string directory) : base(directory) { }
    }
    public abstract class FileRepositoryBase : RepositoryBase<FileInfo, string>, IFileRepository
    {
        public FileRepositoryBase(string baseDirectory) { this.BaseDirectory = new DirectoryInfo(baseDirectory); }

        public DirectoryInfo BaseDirectory { get; set; }
        public override FileInfo GetById(string id)
        {
            FileInfo fileInfo = new FileInfo(id);
            if (fileInfo.Exists)
                return fileInfo;
            return null;
        }

        public override void Add(FileInfo fileInfo)
        {
            if (!fileInfo.Exists)
                fileInfo.Create();
        }

        public void Add(string fileName, Stream stream)
        {
            string savedFileName = Path.Combine(
               BaseDirectory.FullName,
               Path.GetFileName(fileName));
            string content = null;
            using (StreamReader reader = new StreamReader(stream))
            {
                content = reader.ReadToEnd();
                reader.Close();
            }
            File.WriteAllText(savedFileName, content);
        }

        public override void Delete(FileInfo entity)
        {
            if (entity.Exists)
                try
                {
                    entity.Delete();
                }
                catch
                {
                    Debug.WriteLine("Failed to delete file");
                }
        }

        public override List<FileInfo> All()
        {
            return BaseDirectory.GetFiles().ToList();
        }

    }
}
